/*
 * @author java_deng
 * @date 2025/4/5 15:51
 * @description
 */
package org.hbwl.service;

import org.hbwl.dto.Comment;
import org.hbwl.mapper.CommentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentService {
    @Autowired
    private CommentMapper commentMapper;

    public void save(Comment comment) {
        if(comment.getParentId()==null){
            comment.setLevel(1);
            comment.setParentId(0);
        }
        commentMapper.insert(comment);
    }

    public List<Comment> list(Comment comment) {
        List<Comment> list = commentMapper.list(comment);
        List<Comment> parentCommentVoList= list.stream().filter(item->item.getParentId()==0).collect(Collectors.toList());
        for(Comment commentVo:parentCommentVoList){
            commentVo.setCommentList(new ArrayList<>());
        }
        Map<Integer, List<Comment>> parentCommentMap = parentCommentVoList.stream().collect(Collectors.toMap(Comment::getId, Comment::getCommentList));

        for(Comment commentVo: list){
            if(commentVo.getParentId()!=0){
                List<Comment> commentVoList = parentCommentMap.get(commentVo.getParentId());
                commentVoList.add(commentVo);
            }
        }
        return parentCommentVoList;
    }
}
